'use strict';
module.exports = {
	main: async (event) => {
		const db = uniCloud.database();
		const $ = db.command.aggregate;
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		var startTime = Date.now();
		var dailishangzongjinelist = [];
		var dailishangzongjinelist1 = [];
		var dailishanglist = [];
		var pay_rs_num = [];
		var pay_bs_num = [];
		var commission_rate_list = [];
		var commission_rate_list1 = [];
		// const $ = _.aggregate;


		let {
			lastMonthStart,
			lastMonthEnd,
		} = vk.pubfn.getCommonTime(new Date());

		var lastMonth = vk.pubfn.timeFormat(lastMonthStart, "yyyy-MM");

		//查询数据库的a_datas表中是否已存在上个月的代理佣金数据
		let lastMonth_data = await db.collection('a_datas').where({
			month: lastMonth,
			type: 8,
		}).count();
		console.log("lastMonth_data", lastMonth_data.total);
		//如果存在直接终止函数的执行
		if (lastMonth_data.total > 0) {
			return res;
		};

		//获取代理商的的用户数据
		var results = await db.collection('uni-id-users').where({
			role: _.in(["agent"])
		}).field({
			'password': false
		}).get();
		dailishanglist = results.data;
		console.log("获取代理商的的用户数据=>", dailishanglist);

		//获取上个月代理商的引流金额
		for (var i = 0; i <= dailishanglist.length - 1; i++) {
			dailishangzongjinelist[i] = await db.collection('a_recharge').aggregate().match({
				_add_time: _.and(_.gte(lastMonthStart), _.lte(lastMonthEnd)),
				invite_code: dailishanglist[i]._id,
			}).group({
				_id: null,
				totalPrice: $.sum('$shifu_amount')
			}).end();

			//获取付费人数
			let jrczrs = await db.collection('a_recharge')
				.aggregate()
				.match({
					pay_status: 1,
					_add_time: _.and(_.gt(lastMonthStart), _.lt(lastMonthEnd)),
					invite_code: dailishanglist[i]._id
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			pay_rs_num[i] = jrczrs.data.length ? jrczrs.data[0].user_count.length : 0
			
			//获取付费订单笔数
			pay_bs_num[i] = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					pay_status: 1,
					_add_time: _.and(_.gt(lastMonthStart), _.lt(lastMonthEnd)),
					invite_code: dailishanglist[i]._id,
				}
			});


			// commission_rate_list[i] = await db.collection('a_agent_grade').where({
			// 	_id: dailishanglist[i].agent_id,
			// }).field({
			// 	'commission_rate': true,
			// }).get();
			//获取上个月代理商的引流金额换算后的数据
			dailishangzongjinelist1[i] = dailishangzongjinelist[i].data.length == 0 ? 0 :
				dailishangzongjinelist[i].data[0].totalPrice;
			//获取佣金比例
			// commission_rate_list1[i] = commission_rate_list[i].data.length == 0 ? 0 : commission_rate_list[i]
			// 	.data[0].commission_rate;
			commission_rate_list1[i]=dailishanglist[i].commission_rate
			//添加数据到数据库中
			let add_datas = await db.collection('a_datas').add({
				month: lastMonth,
				agent_username: dailishanglist[i].username,
				agent_nickname: dailishanglist[i].nickname,
				agent_id: dailishanglist[i]._id,
				pay_rs_num: pay_rs_num[i],
				pay_bs_num: pay_bs_num[i],
				pay_je_num: dailishangzongjinelist1[i],
				yj_bl: commission_rate_list1[i],
				kn_yj: dailishangzongjinelist1[i] * commission_rate_list1[i],
				type: 8, //0是平台总数据，1是账号级数据，2是链接级数据
				_add_time: new Date().getTime(),
				_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
			});
			console.log("添加代理商上个月的佣金情况数据==》", add_datas);

		};
		console.log("添加数据到数据库中");
		var endTime = Date.now();
		//计算函数运行时间 
		var timeDifference = endTime - startTime;
		//以毫秒为单位，计算出相差的时间 
		var ms = Math.abs(timeDifference);
		//计算相差毫秒数 
		var ms = Math.floor(ms) % 1000;
		//输出结果 
		console.log(ms + "毫秒");
		res.msg = "结束";
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
